#include "timer_impl.h"
#include "timer_module_impl.h"

namespace utility
{
namespace timer_util
{
    timer_impl::timer_impl(timer_module_impl * timer_module, const char * name, uint32 index) :
        _name(name), _next_ticks(0), _timer_module(timer_module), _start_time(time(NULL)),
        _index(index)
    {
        _start_ticks = _timer_module->get_milliseconds();
    }

    timer_impl::~timer_impl(void)
    {
        _timer_module->destroy_timer(this);
    }

    void timer_impl::start()
    {
        _stopped = false;
        _timer_module->start_timer(this);
    }

    void timer_impl::stop()
    {
        _stopped = true;
        _timer_module->stop_timer(this);
    }

    void timer_impl::release()
    {
        delete this;
    }

    void timer_impl::set_start_time(time_t t)
    {
        if (t > _start_time)
        {
            _next_ticks = (t - _start_time) * 1000 + _start_ticks;
            _start_ticks = _next_ticks;
            _start_time = t;
        }
    }

    void timer_impl::trigger(uint32 cur_tick)
    {
        //if (_event)
        //    _event->trigger();
        _event();
        _next_ticks = cur_tick + _interval;
    }

    bool timer_impl::compare::operator ()(timer_impl *t1, timer_impl *t2) const
    {
        int64 d = (int64)(t1->get_next_trigger_time()) - (int64)(t2->get_next_trigger_time());
        if (d == 0)
            return t1->get_index() < t2->get_index();
        else
            return d < 0;
    }
}
}

